<?php

class AbilitiesModel {

	private $_db;

    public function __construct() {
		$this->_db = DBFactory::getDbConnection();
    }

    public function get($id) {
        $id = (int) $id;
        $q = $this->_db->prepare("SELECT id, display, title, text FROM abilities WHERE id=:id");
		$q->execute(array('id'=>$id));
        $data = $q->fetch(PDO::FETCH_ASSOC);
        return new NewsObject($data);
    }

    public function getList($type) {
		switch ($type) {
			case 'full':
				$type = '';
				break;
			case 'display':
				$type = 'WHERE display=1';
				break;
			case 'notdisplay':
				$type = 'WHERE display=0';
				break;
		}
        $q = $this->_db->prepare("SELECT id, display, title, text FROM abilities $type ORDER BY id DESC");
		$q->execute();
        $tabilities = array();
        while ($data = $q->fetch(PDO::FETCH_ASSOC)) {
            $tabilities[] = new AbilitiesObject($data);
        }
        return $tabilities;
    }
	
	//CREATE OBJECT
	public function addObj() {
		$q = $this->_db->prepare("INSERT INTO abilities VALUES(null, '0', 'title', 'text')");
		$q->execute();
		return "1";
	}
	
	//DELETE OBJECT
	public function delObj($id) {
		$id = (int)$id;
		$q = $this->_db->prepare("DELETE FROM abilities WHERE id=:id");
		$q->execute(array('id'=>$id));
		$q->execute();
		//Delete images directory and directory itself
		Tools::removeDir(PATH_DATAS_NEWS.$id.'/tb');
		Tools::removeDir(PATH_DATAS_NEWS.$id);
		return "1";
	}
	
	//DELETE GROUP OF ITEMS SELECTED
	public function delGroup($group) {
		$group = json_decode($group);
		foreach ($group as $key) {
			$this->delObj($key);
		}
		return "1";
	}
	
	//CHECK IF STRING IS JSON
	public function isJson($string) {
		json_decode($string);
		if (json_last_error() == JSON_ERROR_NONE) {
			return true;
		}
	}
	
	//UPDATE OBJECT
	public function upObj($data) {
		if (!is_array($data)) {
			$data = json_decode($data);
		}
		$display = 0;
		foreach ($data as $key) {
			$name = $key->name;
			$value = $key->value;
			switch ($name) {
				case 'id':
					$id = $value;
					break;
				case 'display':
					$display = $value;
				case 'title':
					$title = $value;
					break;
				case 'text':
					$text = $value;
					break;
			}
		}
		$q = $this->_db->prepare("UPDATE abilities SET display=:display, title=:title, text=:text WHERE id=:id");
		$q->execute(array(
			'id'=>$id,
			'display'=>$display,
			'title'=>$title,
			'text'=>$text
		));
		return "1";
	}
	
	public function upAll($dataArray) {
		$dataArray = json_decode($dataArray);
		foreach ($dataArray as $key) {
			$this->upObj($key);
		}
		return "1";
	}
	
	//UPLOAD FILE
	public function upload($id, $dir, $filename, $content) {
		$upload = new Upload();
		$upload->dadUpload($id, $filename, $content, PATH_DATAS.$dir, true);
	}

}

?>